﻿// Deep Earth is a community project available under the Microsoft Public License (Ms-PL)
// Code is provided as is and with no warranty – Use at your own risk
// View the project and the latest code at http://DeepEarth.codeplex.com/

using System.Collections.ObjectModel;
using System.Linq;
using System.Windows.Media;
using GisSharpBlog.NetTopologySuite.Geometries;

namespace DeepEarth.Client.MapControl.Geometries
{
    public class PolygonControl : PathControlBase
    {
        private Brush _fill;

        public PolygonControl()
            : base(new Polygon(null))
        {
            Stroke = new SolidColorBrush(Colors.Black);
            StrokeThickness = 1;
            Fill = new SolidColorBrush(Color.FromArgb(128, 255, 255, 255));
        }

        internal override void UpdateGeometry()
        {
            GeometryItem = new Polygon(new LinearRing(Locations
                .Select(location => new Coordinate(location.Longitude, location.Latitude)).ToArray()));
        }

        internal override void UpdateLocation()
        {
            if (GeometryItem != null)
            {
                Locations = new ObservableCollection<Location>(((Polygon)GeometryItem).ExteriorRing.Coordinates
                    .Select(coordinate => new Location { Longitude = coordinate.X, Latitude = coordinate.Y }).ToList());

                Refresh();
            }
        }

        public override void OnApplyTemplate()
        {
            base.OnApplyTemplate();
            Fill = _fill;
        }

        public override bool IsClosed
        {
            get { return true; }
        }

        ///<summary>
        /// Sets or gets the fill colour for the shape.
        ///</summary>
        public Brush Fill
        {
            get
            {
                return _fill;
            }
            set
            {
                _fill = value;
                if (_Path != null)
                {
                    _Path.Fill = value;
                    if (Layer != null) Layer.UpdateShape(this);
                }
            }
        }
    }
}